package com.example.zhongcao.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.List;
import java.util.Objects;

public class FileUtil {
    private SFTPUtil sftpUtil = new SFTPUtil("root", "zgh/123456", "47.98.175.236", 22);

    public String  updatePics(MultipartFile pic, String dir) throws Exception {
        File f = multipartFileToFile(pic);
        InputStream is = new FileInputStream(f);
        sftpUtil.login();
        sftpUtil.upload(SFTPUtil.basepath, dir, f.getName(), is);
        sftpUtil.logout();
        return SFTPUtil.IP+"/"+dir+"/"+f.getName();
    }

    private static File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile;
        InputStream ins;
        ins = file.getInputStream();
        toFile = new File(Objects.requireNonNull(SFTPUtil.class.getClassLoader().getResource("")).getPath() + Objects.requireNonNull(file.getOriginalFilename()));
        File parent = toFile.getParentFile();
        if (!parent.exists()) {
            parent.mkdir();
        }
        toFile.createNewFile();
        inputStreamToFile(ins, toFile);
        ins.close();

        return toFile;
    }

    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
